const query=require("../utils/query");
const router=require("koa-router")();
const Token=require("../utils/token")

//注册
const addRegister=(data)=>{
  return new Promise((resolve,reject)=>{
    let seaSql=`select * from register where phone = ${data.phone}`;
    query(seaSql,(res)=>{
      if(res.length==0){
        let addSql=`insert into register (phone,username,password) values (${data.phone},'${data.username}',${data.password})`
        query(addSql,(res)=>{
          resolve({
            error:"0",
            msg:"注册成功"
          })
        },(err)=>{
          resolve({
            error:'1',
            msg:"注册失败",
            data:err
          })
        })
      }else{
        resolve({
          error:'2',
          msg:'手机号重复注册'
        })
      }
    },(err)=>{
      resolve({
        error:"500",
        msg:"请求失败",
        data:err
      })
    })
  })
}

//登录
const addLogin=data=>{
  return new Promise((resolve,reject)=>{
    let seaSql=`select * from register where phone=${data.phone} and password=${data.password}`
    query(seaSql,(res)=>{
      if(res.length==1){
        resolve({
          error:"0",
          msg:"登录成功",
          data:{
            id:res[0].id,
            token:Token.encrypt({id:res[0].id},'180')
          }
        })
      }else{
        resolve({
          error:"1",
          msg:"用户名或密码错误"
        })
      }
    },(err)=>{
      resolve({
        error:"500",
        msg:"登录失败",
        data:err
      })
    })
  })
}

const userInfo=data=>{
  return new Promise((resolve,reject)=>{
    let seaSql=`select * from register where id=${data.id}`
    query(seaSql,(res)=>{
      if(res.length>0){
        resolve({
          error:"0",
          data:{
            id:res[0].id,
            username:res[0].username,
            phone:res[0].phone
          }
        })      
      }else{
        resolve({
          error:"1",
          message:"用户ID不正确"
        })
      }
    },err=>{
      resolve({
        error:"500",
        message:"请求失败",
        data:err
      })
    })
  })
}

router
  .post("/signup",async(ctx,next)=>{
    let data=await addRegister(ctx.request.body);
    ctx.body=data;
  })
  .post("/login",async (ctx,nect)=>{
    let data=await addLogin(ctx.request.body);
    ctx.body=data
  })
  .get("/user",async (ctx,next)=>{
    let token=ctx.header.authorization;
    if(token){
      let data=await userInfo(ctx.request.query)
      console.log(data)
      ctx.body=data;
    }else{
      ctx.body={
        error:"255",
        msg:"token失效"
      }
    }
  })

  module.exports=router;